#include "fMainImpl.h"

fMainImpl::fMainImpl(QWidget *parent)
	: QWidget(parent)
{
	m_fMain = new fMain;
	m_fMain->setupUi(this);
	
	m_taskProvider = CTaskProviders::instance();
	m_fMain->cbProviderList->addItems(m_taskProvider->availableTaskProvider());

	createTrayIcon();

	connect(m_fMain->btAdd, SIGNAL(clicked()), this, SLOT(btAddTaskClicked()));
	connect(m_fMain->btRefresh, SIGNAL(clicked()), this, SLOT(btRefreshClicked()));
	connect(m_fMain->eAddTask, SIGNAL(textChanged(QString)), this, SLOT(eAddTaskTextChanged()));
	connect(m_fMain->taskTree, SIGNAL(itemDoubleClicked(QTreeWidgetItem *, int)), this, SLOT(itemDoubleClicked(QTreeWidgetItem *, int)));
}

void fMainImpl::btAddTaskClicked()
{
	// Get provider by name
	ITaskProvider* prov = m_taskProvider->taskProvider(m_fMain->cbProviderList->currentText());
	if(prov)
	{
		STask *task = new STask;
		task->name = m_fMain->eAddTask->text();
		prov->open();
		prov->addTask(task);
		prov->close();
	}
}

void fMainImpl::eAddTaskTextChanged()
{
	m_fMain->btAdd->setEnabled(!m_fMain->eAddTask->text().isEmpty());
}

void fMainImpl::btRefreshClicked()
{
	m_fMain->taskTree->clear();

	foreach(ITaskProvider* tp, m_taskProvider->taskProviders())
	{
		tp->open();
		foreach(STask *tk, tp->getTasks())
		{
			addSTaskInListView(tk);
		}
		tp->close();
	}
}

void fMainImpl::addSTaskInListView(STask *task)
{
	m_fMain->taskTree->addTopLevelItem(new CTaskTreeItem(m_fMain->taskTree, task));
}

void fMainImpl::itemDoubleClicked(QTreeWidgetItem *item, int column)
{
	CTaskTreeItem* taskItm = dynamic_cast<CTaskTreeItem*>(item);
	if(taskItm)
	{
		fTaskImpl *ftask = new fTaskImpl(fTaskImpl::TAM_EDIT);
		ftask->setTask(taskItm->task());
		ftask->show();
	}
}

void fMainImpl::createTrayIcon()
{
	// Actions
	actionTrayOpen = new QAction(QIcon(":/pixmaps/pixmaps/show.png"), tr("Open"), this);
	actionTrayHide = new QAction(QIcon(":/pixmaps/pixmaps/hide.png"), tr("Hide"), this);
	actionTrayQuit = new QAction(QIcon(":/pixmaps/pixmaps/quit.png"), tr("Quit"), this);


	// Menu
	trayMenu = new QMenu(this);
	trayMenu->addAction(actionTrayOpen);
	trayMenu->addAction(actionTrayHide);
	trayMenu->addSeparator();
	trayMenu->addAction(actionTrayQuit);

	// Tray icon
	trayIcon = new QSystemTrayIcon(this);
	trayIcon->setIcon(QIcon(":/logo/pixmaps/toqo.png"));
	trayIcon->setContextMenu(trayMenu);
	trayIcon->show();

	connect(actionTrayQuit, SIGNAL(triggered()), qApp, SLOT(quit()));
	connect(actionTrayOpen, SIGNAL(triggered()), this, SLOT(showNormal()));
	connect(actionTrayHide, SIGNAL(triggered()), this, SLOT(hide()));
	//connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(trayIconClicked(QSystemTrayIcon::ActivationReason)));
}
